package postlogin.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import postlogin.model.UsuarioSlicRol;
import postlogin.service.UsuarioSlicRolLocalServiceUtil;

import com.liferay.portal.kernel.events.Action;
import com.liferay.portal.kernel.events.ActionException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.model.Role;
import com.liferay.portal.model.User;
import com.liferay.portal.service.RoleLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;

public class AsignarRolAction extends Action {

	private static Log _log = LogFactoryUtil.getLog(AsignarRolAction.class);

	@Override
	public void run(HttpServletRequest request, HttpServletResponse response)
			throws ActionException {

		try {
			User user = UserLocalServiceUtil.getUser(Long.valueOf(request.getRemoteUser()));
			List<UsuarioSlicRol> listUsuarioSlicRol = UsuarioSlicRolLocalServiceUtil.findByUsuario(user.getEmailAddress());

			for (UsuarioSlicRol usuarioSlicRol : listUsuarioSlicRol) {
				Role role = RoleLocalServiceUtil.getRole(user.getCompanyId(), usuarioSlicRol.getRol());

				if (role != null) {
					if (!RoleLocalServiceUtil.hasUserRole(user.getUserId(), role.getRoleId())) {
						_log.info("Asignando rol " + role.getName() + " al usuario " + user.getEmailAddress());
						RoleLocalServiceUtil.addUserRoles(user.getUserId(), new long[]{role.getRoleId()});
					}
				}
			}
		}
		catch (Exception e) {
			_log.error(e);
		}

	}

}
